#!/usr/bin/env node

const http = require('http'),
      qs = require('querystring'),
      fs = require('fs'),
      log = console.log;

let items = [];
let result ={
  status:200,
  reason:'OK',
  count:0,
  data:[],
};

http.createServer((req,res)=>{
  logRequest(req);

  if(req.url.slice(0,5)!== '/todo'){
    let html = fs.readFileSync('./template.html').toString('utf8');
    if(req.url ==='/'){
      res.end(html);
    }
    else if(req.url === '/12-todo.js'){
      fs.createReadStream('./12-todo.js').pipe(res);
    }
    else{
      res.end('not api');
    }
    return;
  }
  
  switch(req.method){
    case 'GET':
      select(req,res);
      break;

    case 'POST':
      log('2');
      insert(req,res);
      break;

    case 'PUT':
      updata(req,res);
      break;

    case 'DELETE':
      remove(req,res);
      break;

    default:
      res.end(`${req.method} method not support`);
      break;
  }
}).listen(8080);

function select(req,res){
  result.data = items;
  res.end(JSON.stringify(result));
}

function insert(req,res){
  let data = '';

  req.on('data',chunk => data+=chunk);
  req.on('end',()=>{
    let item = qs.parse(data).item;
    log('1');
    log(item);
    if(item !== '' && typeof item !== undefined){
      log('3');
      items.push(item);
      log(result);
      result.data = items;
      res.end(JSON.stringify(result));
    }else{
      result.status = 401;
      result.reason = 'item is empty';
      res.end(result);
    }
  });
}

function updata(req,res){
  let id = req.url.split(':')[1];
  let data = '';
  req.on('data',chunk=>data+=chunk);
  req.on('end',()=>{
    let item = qs.parse(data).item;
    if(item !== ''&&typeof item !== undefined){
      item[id] = item;
      result.data = items;
      res.end(JSON.stringify(result));
    }else{
      result.status = 402;
      result.reason = 'item is empty';
      res.end(JSON.stringify(result));
    }
  });
}

function remove(req,res){
  
  let id = req.url.split(':')[1];
  if(typeof id === 'undefined'){
    items = [];
    result.status = 200;
    result.reason = 'delete all sucess';
    result.data = items;
    res.end(JSON.stringify(result));
    return;
  }
  items = items.splice(id,1);
  result.status = 200;
  result.reason = 'del sucess';
  res.end(JSON.stringify(result));
}

function logRequest(req){
  log(`${req.method}${req.url}${req.httpVersion}`);
  log(req.headers);
  log();
}
